<?php 

namespace app\admin\controller;

use app\common\model\Tenant;
use app\common\BaseHelper;
use app\common\service\MiniProgramHelp;

use app\admin\model\Producttype;
use app\admin\model\Productdetail;
use app\admin\model\Storeproduct;
//use app\admin\service\Product as ProductService;

use think\Db;
use \think\Request;

/**
 * 商品库管理
 * @Author      jiating
 * @DateTime    2018-04-14
 */
class Product extends Base
{

	public function __construct() {
		parent::__construct();
		$this->model = model('Product');
	}

	public function index() {
		$type = Producttype::where('tenantId',session('TENANT_ID'))->order('orderNo')->select();
		$is_tdt = Tenant::where('id',session('TENANT_ID'))->field('is_tdt')->find();
		$this->assign('type',$type);
		$this->assign('is_tdt',$is_tdt->is_tdt);
		return $this->fetch();
	}

	public function indexApi() {
		$request = Request::instance();
        $param = $request->param();

        $type = Producttype::where('tenantId',session('TENANT_ID'))->select();
        $typeMap = [];
        foreach ($type as $v) {
        	$typeMap[$v['id']] = $v;
        }
        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];  //排序条件
        $where = ['tenantId'=>session('TENANT_ID')];  //搜索条件
        if($param['search']['value']) {  //拼接搜索条件
        	$ss = json_decode($param['search']['value'],true);
        	if($ss['title']){
        		$where['title'] = ['like','%'.$ss['title'].'%'];
            }
        	if($ss['typeId'] && $ss['typeId'] != '0') {
                $where['typeId'] = $ss['typeId'];
            }
        }
        $list = $this->model->where($where)->limit($start,$length)->order($order)->select();
       
		foreach ($list as $k => $v) {
			$tIds = explode(',', $v['typeId']);
			$test = [];
			foreach ($tIds as $kt => $t) {   //显示分类名称
                if(isset($typeMap[$t]) && $typeMap[$t]) {
				    $test['name'][] = $typeMap[$t]['name']; 
                } else {
                    $test['name'][] = '';
                }
			}
			$list[$k]['typeName'] = implode(',', $test['name']);
		}
		$count = $this->model->where($where)->count();
        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];
        return json($res);
	}

	public function addProduct() {
		$typeMdl = new ProductType;
		$type = $typeMdl->where('tenantId',session('TENANT_ID'))->order('orderNo')->select();
		$imgAll = Db::table('image')->where('tenantId',session('TENANT_ID'))->select();
		$this->assign('imgAll',$imgAll);
		$this->assign('type',$type);
		return $this->fetch("product_add");
	}

    public function checkStore() {  //检测是否已有门店，若无，提示去创建门店，并跳转
        $find = \app\admin\model\Store::where('tenantId',session('TENANT_ID'))->find();
        if($find) {
            return true;
        }
        return false;
    }

	public function addProductSave() {
        $check = $this->checkStore();
        if(!$check) {
            return json(['status'=>'2','message'=>'您还没有门店，请去添加']);
        }
		$data = input('post.');
		// return $data;
		// file_put_contents('D:/12.php', "<?php \n ".var_export($data,true).">",FILE_APPEND);
		$data['product']['typeId'] = is_array($data['product']['typeId']) ? implode(',', $data['product']['typeId']) : $data['product']['typeId'];
        $data['product']['imgUrl'] = strpos($data['product']['imgUrl'],'imageView2') > 0 ? $data['product']['imgUrl'] : $data['product']['imgUrl'].'?imageView2/1/w/750/h/560';
        $data['product']['isStore'] = isset($data['product']['isStore']) ? $data['product']['isStore'] : '1';  //库存限制，若未勾选，则限制库存
		$product_id = BaseHelper::getUUID();
		$autoData = [
			'id' => $product_id,
			'tenantId' => session('TENANT_ID'),
			'createDate' => date('Y-m-d H:i:s',time()),
			'updateDate' => date('Y-m-d H:i:s',time()),
			'createOper' => session('member')['id'],
			'updateOper' => session('member')['id'],
            'isVirtual' => 0

		];
		$img = json_decode($data['ProductDtlImg'],true);
		foreach ($img as $v) {
			$imgData[] = $this->imgData(2,$v,$product_id);
		}
		Db::startTrans();
		Db::table('productdtlimg')->insertAll($imgData);
		$productData = array_merge($data['product'],$autoData);  //组装商品数据

		Productdetail::insert(['productId'=>$product_id,'detail'=>$data['detail']]);  //添加详情
		if($data['product']['specClass'] == 2) {
			$productSpec = $data['productSpec'];
			$spec = json_decode($productSpec,true);
			$specData = [];
			foreach ($spec as $v) {
				$v['currentPrice'] = $v['currentPrice'] * 100;
                $v['memberPrice'] = $v['memberPrice'] * 100;
                $v['groupPrice'] = $v['groupPrice'] * 100;
                if($data['product']['isService'] == 2 ) {  //实物商品
                    $v['weight'] = $v['weight'] * 1000;
                }
				$tmp = [
					'id' => get_uniqid_id(),
					'productId' => $product_id,
					'tenantId' => session('TENANT_ID'),
					'createDate' => date('Y-m-d H:i:s',time()),
					'updateDate' => date('Y-m-d H:i:s',time()),
					'createOper' => session('member')['id'],
					'updateOper' => session('member')['id']
				];
				$specData[] = array_merge($v,$tmp);
			}

            foreach ($spec as $k => $v) {   //取得最低价格数据
                if($spec[$k]['currentPrice'] < $spec[0]['currentPrice']) {
                    $tmp = $spec[0];
                    $spec[0] = $spec[$k];
                    $spec[$k] = $tmp;
                }
            }

            // 对多规格商品，将规格中现价最低的价格写入product表
            $productData['currentPrice'] = $spec[0]['currentPrice']*100;
            $productData['memberPrice'] = $spec[0]['memberPrice']*100;
            $productData['groupPrice'] = $spec[0]['groupPrice']*100;
            $productData['integralPrice'] = $spec[0]['integralPrice'];
            $productData['weight'] = $spec[0]['weight'];
            $productData['isStore'] = $spec[0]['isStore'];

			$addSpec = Db::table('productspecgroups')->insertAll($specData);

		}

        // 生成二维码
        $productData['qrCode'] = MiniProgramHelp::getProductQrcode(session('TENANT_ID'), $product_id);

        if(!$productData['qrCode']){
            $productData['qrCode'] = NULL;
        }

        $add = $this->model->insert($productData);
		if($add) {
			Db::commit();
			return json(['status'=>'1','message'=>'修改成功']);
        } else {
        	Db::rollback();
        	return json(['status'=>'2','message'=>'网络出错，请重试']);
        }
	}

	public function editProduct() {

		$id = $this->request->param('id');
		$typeMdl = new ProductType;
		$type = $typeMdl->where('tenantId',session('TENANT_ID'))->order('orderNo')->select();

		$this->assign('type',$type);
		$row = $this->model->where('id',$id)->find();
		$list = Db::table('productdtlimg')->where(['productId'=>$id])->select();
		$imgId = [];
		foreach ($list as $v) {
			$imgId[] = $v['imgId'];
		}

		$this->assign('images',$list);
		if($row['specClass'] == 2) {  //规格参数
			$this->assign('spec',$row['spec']);
		}
		$detail = Productdetail::where('productId',$id)->find();
		$row['detail'] = $detail['detail'];
		$this->assign('row',$row);
        // dump($row);die;
		$this->assign('imgId',implode(',', $imgId));
		return $this->fetch("product_edit");
	}

	/**
	 * 根据商品ID获取规格数据
	 */
	public function getspecDetail() {
		$id = $this->request->param('id');
		$list = Db::table('productspecgroups')->where('productId',$id)->select();
		$return = [
			'status' => '1',
			'recordsFiltered' => 0,
			'recordsTotal' => 0,
			'message' => '',
			'draw' => 0,
			'data' => $list
		];

		return json($return);
	}

	public function editProductSave() {
		$post = input('post.');
		// return $post;

		$data = $post['product'];
        $data['typeId'] = is_array($data['typeId']) ? implode(',', $data['typeId']) : $data['typeId'];
        $data['imgUrl'] = strpos($data['imgUrl'],'imageView2') > 0 ? $data['imgUrl'] : $data['imgUrl'].'?imageView2/1/w/750/h/560';
        $data['isStore'] = isset($data['isStore']) ? $data['isStore'] : '1';  //库存限制，若未勾选，则限制库存

        Db::startTrans();  //启动事务
		//处理轮播图,先将之前上传的且关联image表的图片删除，再新增
        try {
            Db::table('productdtlimg')->where(['tenantId'=>session('TENANT_ID'),'productId'=>$data['id']])->where('imgId','not null')->delete();
            $img = json_decode($post['ProductDtlImg'],true);
            $imgData2 = [];
            foreach ($img as $v) {
                $imgData2[] = $this->imgData(2,$v,$data['id']);
            }
            Db::table('productdtlimg')->insertAll($imgData2);

            if($data['specClass'] == 2) {  //多规格编辑，更新已有规格，插入新增规格,删除（TODO 有未完成订单不能删除）
                $listIds = [];
                $spec = json_decode($post['productSpec'],true);
                $list = Db::table('productspecgroups')->field('id')->where('productId',$data['id'])->select();
                foreach ($list as $l) {
                    $listIds[] = $l['id'];
                }
                $specId = [];
                foreach ($spec as $k => $v) {
                    $spec[$k]['currentPrice'] = $spec[$k]['currentPrice'] * 100;
                    $spec[$k]['memberPrice'] = $spec[$k]['memberPrice'] * 100;
                    $spec[$k]['groupPrice'] =  $spec[$k]['groupPrice'] * 100;
                    if($data['isService'] == 2 ) {  //实物商品
                        $spec[$k]['weight'] = $spec[$k]['weight'] * 1000;
                    }
                    if($v['id']) {
                        $specId[] = $v['id'];
                        $spec[$k]['updateDate'] = date('Y-m-d H:i:s',time());
                        $spec[$k]['updateOper'] = session('member')['id'];
                        Db::table('productspecgroups')->update($spec[$k]);
                    } else {
                        $spec[$k]['id'] = BaseHelper::getUUID();
                        $tmp = [
                            'productId' => $data['id'],
                            'tenantId' => session('TENANT_ID'),
                            'createDate' => date('Y-m-d H:i:s',time()),
                            'updateDate' => date('Y-m-d H:i:s',time()),
                            'createOper' => session('member')['id'],
                            'updateOper' => session('member')['id']
                        ];
                        $arr = array_merge($tmp,$spec[$k]);
                        Db::table('productspecgroups')->insert($arr);
                    }
                    if($spec[$k]['currentPrice'] < $spec[0]['currentPrice']) {
                        $tmp = $spec[0];
                        $spec[0] = $spec[$k];
                        $spec[$k] = $tmp;
                    }
                }
                // 对多规格商品，将规格中现价最低的价格写入product表
                $data['currentPrice'] = $spec[0]['currentPrice'];
                $data['memberPrice'] = $spec[0]['memberPrice'];
                $data['groupPrice'] = $spec[0]['groupPrice'];
                $data['integralPrice'] = $spec[0]['integralPrice'];
                $data['weight'] = $spec[0]['weight'];
                $data['isStore'] = $spec[0]['isStore'];
                        
                $delIds = array_diff($listIds,$specId);   //获取需要删除的货品id
                DB::table('productspecgroups')->where('id','in',implode(',', $delIds))->delete();  //TODO 检查是否有未完成订单
            }

            $data['updateDate'] = date('Y-m-d H:i:s',time());
            $data['updateOper'] = session('member')['id'];

            // 生成二维码
            if(!$data['qrCode']){
                $data['qrCode'] = MiniProgramHelp::getProductQrcode(session('TENANT_ID'), $data['id']);
                if(!$data['qrCode']){
                    $data['qrCode'] = NULL;
                }
            }

            $save =$this->model->update($data);
            Productdetail::where('productId',$data['id'])->update(['detail'=>$post['detail']]);

            Db::commit();
            return json(['status'=>'1','message'=>'修改成功']);
        } catch (Exception $e) {
            Db::rollback();   //回滚事务
            return json(['status'=>'2','message'=>'网络出错，请重试']);
        }        

	}

	public function deleteProduct() {
		$request = Request::instance();
        $id = $request->param('id');
       	// return json(['code'=>'2','message'=>'TODO']);

        $find = Storeproduct::where('product_id',$id)->find();
        if($find) {
            return json(['code'=>'2','message'=>'此商品已被门店选用，不能删除']);
        }

		$where = ['id'=>$id,'tenantId'=>session('TENANT_ID')];
        Db::startTrans();
        try{
            Db::table('productspecgroups')->where('productId',$id)->delete();
            $this->model->where($where)->delete();            
            Db::commit();// 提交事务
            return json(['code'=>'1','message'=>'删除成功']);  
        } catch (\Exception $e) {           
            Db::rollback(); // 回滚事务
            return json(['code'=>'2','message'=>'网络出错，请重试']);
        }

	}

	public function getTypeApi() {
		$request = Request::instance();
        $param = $request->param();

        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];  //排序条件

		$list = Producttype::where('tenantId',session('TENANT_ID'))->limit($start,$length)->order($order)->select();
		$count = Producttype::where('tenantId',session('TENANT_ID'))->count();
        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];
        return json($res);
	}


	public function typeSave() {
		$request = Request::instance();
        $param = $request->param();

        if(isset($param['id']) && $param['id']) {  //编辑操作
        	$param['updateDate'] = date('Y-m-d H:i:s',time());
            $param['updateOper'] = session('member')['id'];
            $upd = Producttype::where('id',$param['id'])->update($param);
            if($upd)
                return json(['code'=>'1','message'=>'保存成功']);
            return json(['code'=>'2','message'=>'出错，请重试']);
        }
        // 添加操作
        $Producttype = new Producttype();
        $Producttype->id = BaseHelper::getUUID();
        $Producttype->orderNo = $param['orderNo'];
        $Producttype->name = $param['name'];
        $Producttype->createDate = date('Y-m-d H:i:s',time());
        $Producttype->updateDate = date('Y-m-d H:i:s',time());
        $Producttype->createOper = session('member')['id'];
        $Producttype->updateOper = session('member')['id'];
        $Producttype->tenantId = session('TENANT_ID');
        if($Producttype->save())
            return json(['code'=>'1','message'=>'保存成功','id'=>$Producttype->id,'name'=>$param['name']]);
        return json(['code'=>'2','message'=>'出错，请重试']);

	}

	/**
	 * 商品类目-删除
	 */
	public function typeDel() {
		$request = Request::instance();
        $id = $request->param('id');

		$typeMdl = new ProductType;
		$where = ['id'=>$id,'tenantId'=>session('TENANT_ID')];
        $product = $this->model->where('typeId',$id)->find();
		if($product) {
			return json(['code'=>'2','message'=>'此类目下有商品，请先删除商品']);
		}
        if($typeMdl->where($where)->delete()) {
        	return json(['code'=>'1','message'=>'删除成功']);
        } else {
        	return json(['code'=>'2','message'=>'出错，请重试']);
        }
	}

	public function typeSort() {

		$typeMdl = new ProductType;
		$post = input('post.');
		$data = [];
		foreach ($post['id'] as $k => $v) {
			$tmp = [
				'id' => $v,
				'orderNo' => $post['order'][$k]
			];
			$data[] = $tmp;
		}
		foreach ($data as $u) {
			$typeMdl->update($u);
		}
		return $this->redirect('addType');
	}

	/**
	 * 组装插入的图片数组，简化代码
	 * @Author   jiating
	 * @DateTime 2018-04-27
	 * @param    int     $type 图片类型，1-主图，2-详情页轮播图
	 * @param    array     $data  图片地址和图片id
	 * @param    int     $pid  关联商品ID
	 * @return   array
	 */
	protected function imgData($type,$data,$pid) {
		$data= [
			'id' =>  BaseHelper::getUUID(),
			'imgId' => $data['imageId'],
			'imgUrl' => strpos($data['imageUrl'],'imageView2') > 0 ? $data['imageUrl'] : $data['imageUrl'].'?imageView2/1/w/750/h/560',
			'productId' => $pid,
			'type' => $type,
			'tenantId' => session('TENANT_ID'),
			'createDate' => date('Y-m-d H:i:s',time()),
			'createOper' => session('member')['id'],
			'updateOper' => session('member')['id']
		];
		return $data;
	}

	/**
	 * 图片组件-获取所有图片-客户端分页
	 * @Author   jiating
	 * @DateTime 2018-05-15
	 */
	public function getList(){
		$list = Db::table('image')->field('')->where('tenantId',session('TENANT_ID'))->order('created DESC')->select();
        $count = Db::table('image')->where('tenantId',session('TENANT_ID'))->count();
        $res = [
            'status' => '1',
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count
        ];
        return json($res);
	}

}